import {parse} from '@babel/parser'
import traverse from '@babel/traverse'
import generate from '@babel/generator'
import t from '@babel/types'

export default function(source)  {
  // source就是读取文件的内容
  // const content = source.replace("小明","黄晓明").replace("18","38");
  // return content;
  
  // if(source.indexOf('name :"login"') !== -1){
  //   console.log(source);
  // }
  // console.log(source);
  // return source

  const ast = parse(source,{
    sourceType:"module"
  })

  // const number = t.numericLiteral(1);

  // console.log(number)
  // const  exp = t.binaryExpression('+',number, number);
  // console.log(exp)
  // const  variable = t.identifier('a');
  // console.log(variable)
  // const  declarations =  t.variableDeclarator(variable, exp);
  // console.log(declarations)

  // 对象表达式  c:c
  const property  =  t.objectProperty(t.identifier('c'), t.stringLiteral('c'));
  //表达式转对象{c:c}
  const obj  = t.objectExpression(
    [
      property
    ]
  )
  //创建代码块  const a = 1; console.log(params); return commonRoutes;
  const fnStatMent = t.blockStatement([
    t.variableDeclaration("const", [
      t.variableDeclarator(
        t.identifier("a"),
        t.numericLiteral(1)
      ),
    ]),
    t.expressionStatement(
      t.callExpression(t.identifier("console.log"), [
        t.identifier("params"),
      ])
    ),
    t.returnStatement(t.identifier("commonRoutes"))
  ])
  //创建函数 function testfnfnfn(params){const a = 1; console.log(params); return commonRoutes;}
  const fn =  t.functionDeclaration(
    t.identifier("testfnfnfn"),
    [t.identifier("params")],
    fnStatMent
  );
  //创建导出 export function testfnfnfn(params){const a = 1; console.log(params); return commonRoutes;}
  const fn2 =  t.ExportNamedDeclaration(fn);

  traverse.default(ast,{
    Identifier(path) {
      // 判断是否是 name 为 n 的标志符
      if (t.isIdentifier(path.node, { name: 'commonRoutes' })) {
        path.container.init.elements.push(obj);
        // console.log(path.container.init.elements.pushContainer('properties',  property))
      }
    },
    // ObjectExpression(path){
        
    //   console.log(path.node,"xxxx")
    //   // path.pushContainer('properties',  property)
    // }
  })
  ast.program.body.push(fn2)
  const out3 = generate.default(ast,{quotes:'single', retainLines:true })
  console.log(out3.code)
  return out3.code;
}